package com.wang.myblog.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.myblog.entity.Comment;
import com.wang.myblog.entity.dto.CommentDto;
import com.wang.myblog.entity.vo.CommentFrom;
import com.wang.myblog.service.CommentService;
import com.wang.myblog.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 博客-评论表 前端控制器
 * </p>
 *
 * @author s
 * @since 2021-05-21
 */
@Api(tags = {"评论管理"})
@CrossOrigin
@RestController
@RequestMapping("/myblog/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @ApiOperation(value = "添加评论")
    @PostMapping("add")
    public R add(@ApiParam(name = "comment", value = "评论信息", required = true)
                 @RequestBody @Validated CommentFrom comment) {
        if (StringUtils.isEmpty(comment.getPid())) {
            comment.setPid(0L);//-前端不传或者传0，则表示为一级评论
        } else {
            if (StringUtils.isEmpty(comment.getReplyUser())) {
                return R.error("用户名不能为空！");
            }
        }
        Comment commentDb = new Comment();
        BeanUtils.copyProperties(comment, commentDb);

        return R.add(commentService.save(commentDb));
    }

    //根据sid查询其评论信息
    @ApiOperation(value = "添加评Get论")
    @GetMapping("comment/{sid}")
    public R getComment(@ApiParam(name = "current", value = "当前页", required = false, defaultValue = "1")
                        @PathVariable(value = "current", required = false) Integer current,
                        @ApiParam(name = "size", value = "每页显示条数", required = false, defaultValue = "10")
                        @PathVariable(value = "size", required = false) Integer size,
                        @ApiParam(name = "sid", value = "被评论的文章或者页面的ID", required = true)
                        @PathVariable(value = "sid", required = true) Long sid) {
        Page<CommentDto> page = new Page<>(current, size);
        commentService.getTreeCommentBySid(sid, page);

        return R.ok().data("total", page.getTotal()).data("size", page.getSize()).data("current", page.getCurrent())
                .data("pages", page.getPages()).data("records", page.getRecords());
    }

}

